/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.legendshop.dao.support.PageSupport;
import com.legendshop.dao.support.ToolBarProvider;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.AttachmentTypeEnum;
import com.legendshop.oa.constants.CommonPage;
import com.legendshop.oa.constants.Constants;
import com.legendshop.oa.constants.ImageTypeEnum;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.handler.AttachmentManager;
import com.legendshop.oa.model.Attachment;
import com.legendshop.oa.model.AttachmentTree;
import com.legendshop.oa.model.ToolBarSupportDto;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.service.AttachmentService;
import com.legendshop.oa.service.AttachmentTreeService;
import com.legendshop.oa.tag.page.PageProviderImpl;
import com.legendshop.util.AppUtils;
/**
 * 图片空间
 *
 */
@Controller
@RequestMapping("/imageAdmin")
public class ImagesController extends BaseController{
	
	/** The log. */
	private final static Logger log = LoggerFactory.getLogger(ImagesController.class);
	
	@Autowired
    private AttachmentService attachmentService;
	
	@Autowired
    private AttachmentTreeService attachmentTreeService;
	
	@Autowired
	private AttachmentManager attachmentManager;
	
	
	/**
	 * 图片空间 页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/query")
    public String query(HttpServletRequest request, HttpServletResponse response) {
		Long userId = UserManager.getUserId(request);
		
		if(AppUtils.isBlank(userId)){
			return null;
		}
		
        return PathResolver.getPath(request, response, CommonPage.IMAGE_LIST_QUERY);
    }
	
	/**
	 * 图片控件 页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/prop")
    public String prop(HttpServletRequest request, HttpServletResponse response) {
		Long userId = UserManager.getUserId(request);
		if(AppUtils.isBlank(userId)){
			log.warn("visit prop userId is null and return");
			return null;
		}
        return PathResolver.getPath(request, response, CommonPage.IMAGE_PROP_QUERY);
    }
	
	/**
	 * 图片控件 页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/remoteImages")
    public String remoteImages(HttpServletRequest request, HttpServletResponse response) {
		Long userId = UserManager.getUserId(request);
		if(AppUtils.isBlank(userId)){
			log.warn("visit img remoteImages, userId is null and return");
			return null;
		}
        return PathResolver.getPath(request, response, CommonPage.IMAGE_REMOTE_QUERY);
    }
	
	/**
	 * 获取父目录 获取子目录
	 * @param request
	 * @param response
	 * @param parentId
	 * @return
	 */
	@RequestMapping("/getChildTree")
	public @ResponseBody List<AttachmentTree>  getChildTree(HttpServletRequest request, HttpServletResponse response,Long parentId) {
		Long userId = UserManager.getUserId(request);
		if(AppUtils.isBlank(userId)){
			return null;
		}
		String userName = UserManager.getUserName(request);
		List<AttachmentTree> attmntTrees = null;
		if(parentId==null){
			attmntTrees = new ArrayList<AttachmentTree>();
			AttachmentTree attachmentTree = new AttachmentTree();
			attachmentTree.setId(0l);
			attachmentTree.setName("根目录");
			attachmentTree.setParentId(0l);
			attachmentTree.setUserName(userName);
			attachmentTree.setIsParent(true);
			attachmentTree.setOpen(true);
			attmntTrees.add(attachmentTree);
		}else{
			attmntTrees = attachmentTreeService.getAttachmentTreeByPid(parentId,userName);
		}
		return attmntTrees;
	}
	
	/**
	 * 图片空间 获取目录下的图片
	 * @param request
	 * @param response
	 * @param treeId
	 * @param curPageNO
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/getChildImg")
	public @ResponseBody ToolBarSupportDto getChildImg(HttpServletRequest request, HttpServletResponse response,Long treeId, String curPageNO,String shopName,String searchName) throws IOException {
		PageSupport<Attachment> ps = attachmentService.getAttachment(shopName, 1, 1, 21, curPageNO, searchName, ImageTypeEnum.IMG.value());
		ToolBarProvider provider = new PageProviderImpl(ps);
		ToolBarSupportDto dto = new ToolBarSupportDto(ps, provider.getToolBar());
		return dto;

	}
	
	
	/**
	 * 删除图片
	 * @param request
	 * @param response
	 * @param attachmentId 附件Id
	 * @return
	 */
	@RequestMapping("/delImg")
	public @ResponseBody String delImg(HttpServletRequest request, HttpServletResponse response,Long attachmentId)  {
		if(attachmentId == null){
			log.warn("delImg but attachmentId is null");
			return "主键为空";
		}
		//管理员可以删除图片
		Attachment attachment = attachmentService.getAttachment(attachmentId);
		if(AppUtils.isNotBlank(attachment)){
			//删除附件表记录
			attachmentService.deleteAttachment(attachment);
			//删除文件
			attachmentManager.deleteTruely(attachment.getFilePath());
		}
		return Constants.SUCCESS;
		

	}
	
	/**
	 * 图片批量上传
	 * @param request
	 * @param response
	 * @param treeId
	 * @param file
	 * @return
	 */
	@RequestMapping("/uploadImg")
	public @ResponseBody String uploadImg(HttpServletRequest request, HttpServletResponse response,Integer treeId,@RequestParam("files") MultipartFile[] files)  {
		Long userId = UserManager.getUserId(request);
		if(AppUtils.isBlank(userId)){
			log.warn("uploadImg but userId is null");
			return null;
		}
		UserDetail userDetail = UserManager.getUser(request);
		if(AppUtils.isNotBlank(files)){
			for(int i=0;i<files.length;i++){
				MultipartFile file = files[i];
				String filePath = attachmentManager.upload(file);
				attachmentManager.saveAttachment(userDetail.getUserId(),userDetail.getUsername(), filePath, file, AttachmentTypeEnum.PRODUCT,treeId, ImageTypeEnum.IMG);
			}
		}
		return Constants.SUCCESS;
	}
	
	/**
	 * 修改图片名称
	 * @param request
	 * @param response
	 * @param filePath
	 * @param fileName
	 * @return
	 */
	@RequestMapping("/renameImg")
	public @ResponseBody String renameImg(HttpServletRequest request, HttpServletResponse response,String filePath,String fileName)  {
		Long userId = UserManager.getUserId(request);
		if(AppUtils.isBlank(userId)){
			log.warn("renameImg but userId is null");
			return null;
		}
		attachmentService.updateAttachmentFileNameByFilePath(filePath, fileName);
		return Constants.SUCCESS;
	}
	
	/**
	 * 修改目录名称
	 * @param request
	 * @param response
	 * @param id
	 * @param name
	 * @return
	 */
	@RequestMapping("/renameTree")
	public @ResponseBody String renameTree(HttpServletRequest request, HttpServletResponse response,Integer id,String name)  {
		Long userId = UserManager.getUserId(request);
		if(AppUtils.isBlank(userId)){
			log.warn("renameTree but userId is null");
			return null;
		}
		attachmentTreeService.updateAttmntTreeNameById(id,name);
		return Constants.SUCCESS;
	}
	
	/**
	 * 添加目录
	 * @param request
	 * @param response
	 * @param id
	 * @param name
	 * @return
	 */
	@RequestMapping("/addTree")
	public @ResponseBody Long addTree(HttpServletRequest request, HttpServletResponse response,Long id,String name)  {
		Long userId = UserManager.getUserId(request);
		if(AppUtils.isBlank(userId)){
			log.warn("addTree but userId is null");
			return null;
		}
		String userName = UserManager.getUserName(request);
		AttachmentTree attachmentTree = new AttachmentTree();
		attachmentTree.setName(name);
		attachmentTree.setParentId(id);
		attachmentTree.setUserName(userName);
		attachmentTree.setIsParent(true);
		attachmentTree.setOpen(true);
		return attachmentTreeService.saveAttachmentTree(attachmentTree);
	}
	
	/**
	 * 删除目录 和 目录下的所有子目录 和图片
	 * @param request
	 * @param response
	 * @param treeId 目录id
	 * @return
	 */
	@RequestMapping(value = "/delTreeAndPic", method = RequestMethod.POST)
	public @ResponseBody String delTreeAndPic(HttpServletRequest request, HttpServletResponse response,Long treeId)  {
		//根节点 不能删除
		if(treeId==null || treeId==0){
			log.warn("delTreeAndPic but 根节点不能删除");
			return Constants.FAIL;
		}
		//查询该节点是否属于该用户,然后进行递归查出该目录 的所有子目录 和 文件,最后删除
		AttachmentTree attachmentTree = attachmentTreeService.getAttachmentTree(treeId);
		if(AppUtils.isNotBlank(attachmentTree)){
			//递归查出该节点 的所有子目录
			List<AttachmentTree> attmntTreeList = attachmentTreeService.getAllChildByTreeId(treeId);
			//找出所有子目录下的附件记录
			List<Attachment> attmntList  = attachmentService.getAttachmentByTrees(attmntTreeList);
			if(AppUtils.isNotBlank(attmntList)){
				//删除所有附件记录
				attachmentService.deleteAttachment(attmntList);
				for (Attachment attachment : attmntList) {
					//删除文件
					attachmentManager.deleteTruely(attachment.getFilePath());
				}
			}
			//删除所有目录
			attachmentTreeService.deleteAttachmentTree(attmntTreeList);
		}
		return Constants.SUCCESS;
	}
}
